package com.junzhiit.nengji.cms.service.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.junzhiit.nengji.bo.PromotionPosterBO;
import com.junzhiit.nengji.cms.service.PromotionPosterService;
import com.junzhiit.nengji.cms.web.exception.ShopNotFoundException;
import com.junzhiit.nengji.cms.web.util.FileUtil;
import com.junzhiit.nengji.cms.web.util.ViewObjectUtil;
import com.junzhiit.nengji.cms.web.util.aliyun.AliyunOSSClientUtil;
import com.junzhiit.nengji.cms.web.vo.DataTablesParamVO;
import com.junzhiit.nengji.cms.web.vo.PromotionPosterVO;
import com.junzhiit.nengji.cms.web.vo.ResultVO;
import com.junzhiit.nengji.cms.web.vo.SystemUserSessionVO;
import com.junzhiit.nengji.dao.ChainDAO;
import com.junzhiit.nengji.dao.PromotionPosterDAO;
import com.junzhiit.nengji.dao.ShopDAO;
import com.junzhiit.nengji.dao.cache.SystemUserCacheDAO;
import com.junzhiit.nengji.dao.util.DIYKey;
import com.junzhiit.nengji.model.Chain;
import com.junzhiit.nengji.model.PromotionPoster;
import com.junzhiit.nengji.model.Shop;
import com.junzhiit.nengji.model.enums.SystemUserType;

@Service
public class PromotionPosterServiceImpl implements PromotionPosterService {

	@Autowired
	PromotionPosterDAO promotionPosterDAO;

	@Autowired
	SystemUserCacheDAO systemUserCacheDAO;

	@Autowired
	ChainDAO chainDAO;

	@Autowired
	ShopDAO shopDAO;

	@Value("${upload.temp}")
	private String tempPath;

	@Value("${oss.backet.name}")
	private String backetName;

	@Value("${upload.mall.promotion.poster}")
	private String posterPath;
	
	@Value("${oss.url}")
	private String url;

	@Override
	public ResultVO promotionPosterSet(PromotionPosterVO ppv) {
		ResultVO result = new ResultVO();
		PromotionPoster pp = new PromotionPoster();
		BeanUtils.copyProperties(ppv, pp);
		SystemUserSessionVO sessionVO = systemUserCacheDAO.getHash(DIYKey.getSessionHashKey(ppv.getSessionId()),
				SystemUserSessionVO.class);
		Integer loginType = sessionVO.getLoginType();
		if (loginType == SystemUserType.INTERNAL.toIntStatus()) {
			pp.setPlatform(SystemUserType.INTERNAL.toIntStatus());
		}
		String systemId = sessionVO.getSystemId();
		if (loginType == SystemUserType.SHOP.toIntStatus()) {
			Chain chain = chainDAO.query(systemId);
			Shop shop = shopDAO.query(systemId);
			if (chain == null && shop == null) {
				throw new ShopNotFoundException("店铺/品牌不存在");
			}
			pp.setPlatform(SystemUserType.SHOP.toIntStatus());
			pp.setCsId(systemId);
		}
		Boolean rlt = false;
		PromotionPoster ppResult=new PromotionPoster();
		if (StringUtils.isNotBlank(pp.getId())) {
			rlt = promotionPosterDAO.update(pp);
		} else {
			ppResult = promotionPosterDAO.insert(pp);
		}
		if (rlt || ppResult != null) {
			if (StringUtils.isNotBlank(pp.getSrcImg())) {
				boolean is = AliyunOSSClientUtil.moveFile(backetName, pp.getSrcImg(), posterPath, tempPath);
				if (is) {
					AliyunOSSClientUtil.removeFile(backetName, tempPath + pp.getSrcImg());
				}
			}
			if (StringUtils.isNotBlank(pp.getIcon())) {
				boolean is = AliyunOSSClientUtil.moveFile(backetName, pp.getIcon(), posterPath, tempPath);
				if (is) {
					AliyunOSSClientUtil.removeFile(backetName, tempPath + pp.getIcon());
				}
			}
			if (StringUtils.isNotBlank(pp.getFileName())) {
				boolean is = AliyunOSSClientUtil.moveFile(backetName, pp.getFileName(), posterPath, tempPath);
				if (is) {
					AliyunOSSClientUtil.removeFile(backetName, tempPath + pp.getFileName());
				}
			}
		}
		return result;
	}

	@Override
	public Map<String, Object> findAll(DataTablesParamVO dtp, PromotionPosterVO ppv) {
		PromotionPosterBO ppb = new PromotionPosterBO();
		BeanUtils.copyProperties(ppv, ppb);
		SystemUserSessionVO sessionVO = systemUserCacheDAO.getHash(DIYKey.getSessionHashKey(ppv.getSessionId()),
				SystemUserSessionVO.class);
		Integer loginType = sessionVO.getLoginType();
		if (loginType == SystemUserType.INTERNAL.toIntStatus()) {
			ppb.setPlatform(SystemUserType.INTERNAL.toIntStatus());
		}
		String systemId = sessionVO.getSystemId();
		if (loginType == SystemUserType.SHOP.toIntStatus()) {
			Chain chain = chainDAO.query(systemId);
			Shop shop = shopDAO.query(systemId);
			if (chain == null && shop == null) {
				throw new ShopNotFoundException("店铺/品牌不存在");
			}
			ppb.setPlatform(SystemUserType.SHOP.toIntStatus());
			ppb.setCsId(systemId);
		}
		List<PromotionPosterBO> ppList = promotionPosterDAO.getAllList(ppb, dtp.getStart(), dtp.getLength());
		int totalCount = promotionPosterDAO.getTotalCount(ppb);
		return ViewObjectUtil.dataTables(ppList, dtp.getDraw(), totalCount);

	}

	@Override
	public ResultVO findById(PromotionPosterVO ppv) {
		ResultVO result = new ResultVO();
		PromotionPosterBO ppb = new PromotionPosterBO();
		BeanUtils.copyProperties(ppv, ppb);
		PromotionPosterBO ppbo = promotionPosterDAO.findById(ppb);
		if (ppbo!= null) {
			if (StringUtils.isNotBlank(ppbo.getSrcImg())) {
				AliyunOSSClientUtil.moveFile(backetName, ppbo.getSrcImg(), tempPath, posterPath);
			}
			if (StringUtils.isNotBlank(ppbo.getIcon())) {
				AliyunOSSClientUtil.moveFile(backetName, ppbo.getIcon(), tempPath, posterPath);
			}
		}
		result.setData(ppbo);
		return result;
	}

	@Override
	public void download(HttpServletResponse response, HttpServletRequest request, PromotionPosterVO ppv) {
		URL urlPath;
		try {
			urlPath = new URL(url + posterPath + ppv.getFileName());
			HttpURLConnection conn = (HttpURLConnection) urlPath.openConnection();
			InputStream is;
			is = conn.getInputStream();
			File targetFile = new File(tempPath + ppv.getFileName());
			saveFile(is, targetFile);
			FileUtil.download(request, response, tempPath + ppv.getFileName());
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void saveFile(InputStream is, File targetPath) {
		FileOutputStream fos = null;
		File parentFile = targetPath.getParentFile();
		if (!parentFile.exists()) {
			parentFile.mkdirs();
		}
		try {
			fos = new FileOutputStream(targetPath);
			byte[] buff = new byte[1024 * 4];
			int len;
			while ((len = is.read(buff)) != -1) {
				fos.write(buff, 0, len);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (is != null) {
					is.close();
				}
				if (fos != null) {
					fos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
